#-*-coding:utf-8-*-
'''
@ info: gmail manage!
@ date: 2012-09-06
@ author: huangzy
'''
import urllib  
import urllib2 
import sys, httplib, os,check
from django.conf import settings
from crm.models import Members
from crm.models import Agent 
from crm.models import smtplog
from crm.models import smtpmaillog
from crm.models import smtpsendmaligroup
from crm.models import smtpsendmalilist
from crm.models import smtpsendermaillist
from crm.models import Projects
from models import Salesperson,Role
from models import Salesperson_groups
from django.shortcuts import get_object_or_404,render_to_response
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django import forms
from django.core.paginator import Paginator, InvalidPage
import grap_mail_api as grap
from datetime import datetime
from django.db.models import Q
from django.db import connection

import logClass as log

log = log.Log()

def post(url,data):  
    try:
        req = urllib2.Request(url)  
        data = urllib.urlencode(data)  
        #enable cookie  
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())  
        response = opener.open(req, data)  
        ret = response.read()
        return ret
    except Exception,e:
        log.error('%s'%e)
        return '''{"code":0,"msg":"%s"}'''%e

def sendmail(request):
    '''发送邮件页面和处理ajax发送邮件'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    
    cursor=connection.cursor()
    sql = """select `group` from `crm_smtpsendermaillist` where `is_removed`=0 and `status`>0 group by `group` order by `group`"""
    cursor.execute(sql)
    groups = cursor.fetchall()

    return render_to_response('smtpmail/sendmail.html',{'groups':groups})

def sendphpmail(request):
    '''发送邮件页面和处理ajax发送邮件'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    
    if request.is_ajax():
        groupid = request.POST.get('groupid','')
        sendgroup = request.POST.get('sendgroup',1)
        delay = request.POST.get('delay',0)
        obj = request.POST.get('obj','')
        content = request.POST.get('content','')
        
        if not groupid:
            return HttpResponse('''{"code":0,"msg":"Mail receiving people can't be empty!"}''')
        if  not obj:
            return HttpResponse('''{"code":0,"msg":"The mail subject can't for empty!"}''')
        if  not content:
            return HttpResponse('''{"code":0,"msg":"The mail content can't for empty!"}''')
        
        data = {'groupid':groupid,'sendgroup':sendgroup,'delay':delay,'content':content.encode('utf8'),'obj':obj.encode('utf8'),'senduser':request.session['name']}
        url = settings.PHPSENDMAIL
        ret = post(url,data)
        return HttpResponse(ret)
    return render_to_response('error/404.shtml')

def matchmail(request):
    '''发送邮件页面和处理ajax发送邮件'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    
    page=int(request.GET.get('page',1))
    pagesize = int(request.GET.get('ps',15))
    is_con = int(request.GET.get('is_con',0))

    begin = (request.GET.get('begin',''))
    end = (request.GET.get('end',''))
    object = (request.GET.get('object',''))
    senduser = (request.GET.get('senduser',''))
    sendmail = (request.GET.get('sendmail',''))

    maillogs = smtplog.objects.filter(is_removed=0).order_by('-id')
    if begin:
        maillogs = maillogs.filter(mail_sendtime__gte=begin)
    if end:
        maillogs = maillogs.filter(mail_sendtime__lte=end)
    if object:
        #maillogs = maillogs.filter(mail_object__iexact=object)
        objectup=object.capitalize()
        maillogs=maillogs.filter(Q(mail_object__icontains=object)|Q(mail_object__icontains=objectup))
    if senduser:
        userup = senduser.capitalize()
        maillogs = maillogs.filter(Q(mail_senduser__icontains=senduser)|Q(mail_senduser__icontains=userup))
    if sendmail:
        maillogs = maillogs.filter(mail_sendmail__icontains=sendmail)

    paginator=Paginator(maillogs,pagesize)
    tolpage = len(range(paginator.num_pages+1)[1:])
    maillogs = maillogs[(page-1)*pagesize:(page)*pagesize]

    return render_to_response('smtpmail/matchmail.html',{
        'tolpage':tolpage,
        'page':page,
        'ps':pagesize,
        'is_con':is_con,
        'mails':maillogs,
        'begin':begin,
        'end':end,
        'object':object,
        'sneduser':senduser,
        'sendmail':sendmail,
        'ttt':''
    })

def getsendstate(request):
    '''获取邮件发送结果统计'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    
    if request.is_ajax():
        sid = request.GET.get('mid','')
        if not sid:
            return HttpResponse('''{"code":0,"msg":"Please try again after to refresh the page"}''')
        
        ecode = 0
        einfo = 'System Error!'

        try:
            '''
                send_state: 1-失败，2-成功，3-打开，4-退订 0-其它原因发送失败
            '''
            totalsend = smtpmaillog.objects.filter(send_id=sid,send_state__gte=0)
            sendtol = len(totalsend)
            fail = len(totalsend.filter(send_state__lte=1))
            opend = len(totalsend.filter(send_state=3))
            unsub = len(totalsend.filter(send_state=4))
            
            ecode = 1
            einfo = '''%s,%s,%s,%s,%s'''%(sendtol,sendtol-fail,fail,opend,unsub)
        except Exception,e:
            log.error(`e[0]`)

        return HttpResponse('''{"code":%s,"msg":"%s"}'''%(ecode,einfo))
    return render_to_response('error/404.shtml')

def smailinfo(request):
    '''查看邮件内容'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    
    sid=int(request.GET.get('mlid',''))
    if not sid:
        return render_to_response('error/404.shtml')
    try:
        mailinfo = smtplog.objects.get(pk=sid)
        content = mailinfo.mail_content.tostring()
        object = mailinfo.mail_object
    except Exception,e:
        log.error(`e[0]`)
        content = 'Content is empty!'
        object = 'Content is empty!'
    return render_to_response('smtpmail/smailinfo.html',{'object':object,'mailcon':content,'ttt':''})

def optstate(request):
    '''统计邮件打工、退订状态'''
    email=request.GET.get('m','')
    opt=request.GET.get('opt','')
    sendid = request.GET.get('sid','')
    
    try:
        if opt and email:
            if opt=='open':
                cursor=connection.cursor()
                sql = """update `crm_smtpmaillog` set `send_state`=3 where `mail_sendmail`='%s' and `send_state` in (1,2) and send_id='%s'"""%(email,sendid)
                cursor.execute(sql)
                cursor.connection.commit()
                cursor.close();
                return HttpResponse('''''')
            elif opt=='unsub':
                cursor=connection.cursor()
                sql = """update `crm_smtpmaillog` set `send_state`=4 where `mail_sendmail`='%s' and `send_state` in (1,2,3) and send_id='%s'"""%(email,sendid)
                sql1 = """update `crm_smtpsendmalilist` set `send_state`=4 where `mail_sendmail`='%s' and `send_state` in (1,2,3)"""%(email)
                sql2 = """update `crm_members` set `email_state`=0 where `email`='%s'"""%email;
                cursor.execute(sql)
                cursor.connection.commit()
                cursor.execute(sql1)
                cursor.connection.commit()
                cursor.execute(sql2)
                cursor.connection.commit()
                cursor.close();
                return HttpResponse('''退订成功，我们以后将不会再发送此类邮件到您的邮箱，谢谢您的支持！''')
        else:
            return HttpResponse('''else 部分%s,%s'''%(opt,email))
    except Exception,e:
        log.error(e)
    return HttpResponse('''%s,%s,%s'''%(e,opt,email))
    
def selectuser(request):
    '''发送邮件页面和处理ajax发送邮件'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    
    agent_list = Agent.objects.order_by('id')
    project_list = Projects.objects.order_by('id')
    group_list = Salesperson_groups.objects.order_by('id')
    
    if request.method == 'GET':
        page=int(request.GET.get('page',1))
        pagesize = int(request.GET.get('ps',9))
        p_id=request.GET.get('p_id',0)
        is_con = int(request.GET.get('is_con',0))
        a_id=request.GET.get('a_id',0)
        g_id=request.GET.get('g_id',0)
        sales=request.GET.get('sales','')
        name=request.GET.get('name','')
        tel=request.GET.get('tel','')
        
        members = Members.objects.filter(is_removed=0,email_state=1)
        
        where = ''

        if int(p_id) !=0:
            members = members.filter(projects=p_id)
        if int(a_id) !=0:
            members = members.filter(agent=a_id)
        if int(g_id) !=0:
            members = members.filter(men_area=g_id)
        if sales:
            salesup=sales.capitalize()
            members=members.filter(Q(salesperson__name__icontains=sales)|Q(salesperson__name__icontains=salesup))
        if name:
            nameup=name.capitalize()
            members=members.filter(Q(name__icontains=name)|Q(name__icontains=nameup))
        if tel:
            members=members.filter(Q(tel_h__contains=tel)|Q(tel_o__contains=tel)|Q(tel_m__contains=tel))
        #limit = '%s,%s'%((page-1)*pagesize,pagesize)
        
        '''
        from django.db import connection
        cursor=connection.cursor()
        cursor1=connection.cursor()
        sql = 'select name,email from `crm_members` where 1=1 %s group by `email` limit %s'%(where,limit)
        sql1 = 'select count(1) from `crm_members` where id in(SELECT id FROM `crm_members` WHERE 1 =1 %s GROUP BY `email`)'%where
        cursor.execute(sql)
        members = cursor.fetchall()
        cursor1.execute(sql1)
        tol = cursor1.fetchall()
        
        if len(tol)>0:
            tolpage = int(int(tol[0][0])/pagesize)
            if int(tol[0][0])%pagesize !=0:
                tolpage = tolpage+1
        else:
            tolpage = 1
        '''
        #tolpage = 3
        paginator=Paginator(members,pagesize)
        tolpage = len(range(paginator.num_pages+1)[1:])
        members = members[(page-1)*pagesize:(page)*pagesize]
    return render_to_response('smtpmail/selectmail.html',{
        'project_list':project_list,
        'agent_list':agent_list,
        'group_list':group_list,
        'sales':sales,
        'a_id':a_id,
        'p_id':p_id,
        'g_id':g_id,
        'name':name,
        'tel':tel,
        'is_con':is_con,
        'members':members,
        'tolpage':tolpage,
        'pagesize':pagesize,
        'page':page,
        'ttt':''
    })

def screatlist(request):
    '''创建邮件联系人组列表'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    
    if request.is_ajax():
        maillist = request.POST.get('maillist','')
        listname = request.POST.get('listname','')
        host = request.POST.get('host','')
        listid = request.POST.get('listid','')
        this_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S');
        ecode = 0
        einfo = 'System Error!'

        if not maillist or not listname:
            return HttpResponse('''{"code":0,"msg":"Please try again after to refresh the page"}''')
        
        oldlist = smtpsendmaligroup.objects.filter(is_removed__lt =1,group_name=listname).order_by('id')

        if len(oldlist)>0:
            return HttpResponse('''{"code":0,"info":"List Name already exists!"}''')
        del(oldlist)
        try:
            groups = smtpsendmaligroup(
                group_name = listname,
                add_time = this_time,
                add_user = request.session['name']
            )
            groups.save()
            group = smtpsendmaligroup.objects.filter(is_removed=0,group_name=listname).order_by('id')
            for g in group:
                groupid = g.id
            
            maillists = maillist[1:].split(',')
            for m in maillists:
                info = m.split('#')
                lists = smtpsendmalilist(
                    mail_sendmail = info[1],
                    user_name = info[0],
                    mailgroup_id=groupid
                )
                lists.save()
            ecode = 1
            einfo = 'Successful'
        except Exception,e:
            log.error(`e[0]`)
        return HttpResponse('''{"code":%s,"msg":"%s"}'''%(ecode,einfo))
    return render_to_response('error/404.shtml')
    
def smaillist(request):
    '''邮件联系人组列表'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')

    page=int(request.GET.get('page',1))
    pagesize = int(request.GET.get('ps',10))
    is_con = int(request.GET.get('is_con',0))

    listname = request.GET.get('listname','')
    adduser = request.GET.get('adduser','')
    
    where = ''
    if listname:
        where += """ and `group_name` like '%%%%%s%%%%' """%listname
    
    if adduser:
        where += """ and `add_user` like '%%%%%s%%%%' """%adduser
    limit = '%s,%s'%((page-1)*pagesize,pagesize)

    cursor=connection.cursor()
    sql = """select * from `crm_smtpsendmaligroup` where `is_removed`=0 %s order by `id` desc limit %s"""%(where,limit)
    sql1 = """select count(*) as num from `crm_smtpsendmaligroup` where  `id` in(select id from `crm_smtpsendmaligroup` where `is_removed`=0 %s) """%where
    cursor.execute(sql)
    mails = cursor.fetchall()
    cursor.execute(sql1)
    tol = cursor.fetchall()
    cursor.close();

    if len(tol)>0:
        tolpage = int(int(tol[0][0])/pagesize)
        if int(tol[0][0])%pagesize !=0:
            tolpage = tolpage+1
    else:
        tolpage = 1

    return render_to_response('smtpmail/smaillist.html',{
        'tolpage':tolpage,
        'page':page,
        'ps':pagesize,
        'listname':listname,
        'adduser':adduser,
        'is_con':is_con,
        'mails':mails,
        'ttt':''
    })

def optsmaillist(request):
    '''邮件联系人组列表'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    
    if request.is_ajax():
        opt = request.GET.get('opt','')
        mid = request.GET.get('id','')
        if not opt or not mid :
            return HttpResponse('''{"code":0,"msg":"Please try again after to refresh the page_%s_%s"}'''%(opt,mid))
        
        ecode = 0
        einfo = 'System Error!'
        
        if opt=='del':
            try:
                mailgroup = smtpsendmaligroup.objects.get(pk=mid)
                mailgroup.is_removed = 1
                mailgroup.save()
                ecode = 1
                einfo = 'suc'
            except Exception,e:
                log.error(e)
        elif opt=='watch':
            try:
                page=int(request.GET.get('page',1))
                pagesize = int(request.GET.get('ps',10))

                groupmails = smtpsendmalilist.objects.filter(mailgroup_id=mid)
                paginator=Paginator(groupmails,pagesize)
                tolpage = len(range(paginator.num_pages+1)[1:])
                groupmails = groupmails[(page-1)*pagesize:(page)*pagesize]
                return render_to_response('smtpmail/groupmails.html',{
                    'mails':groupmails,
                    'page':page,
                    'ps':pagesize,
                    'tolpage':tolpage,
                    'mid':mid
                })
            except Exception,e:
                log.error(e)

        elif opt=='watchsendinfo':
            try:
                page=int(request.GET.get('page',1))
                pagesize = int(request.GET.get('ps',10))

                groupmails = smtpmaillog.objects.filter(send_id=mid)
                paginator=Paginator(groupmails,pagesize)
                tolpage = len(range(paginator.num_pages+1)[1:])
                groupmails = groupmails[(page-1)*pagesize:(page)*pagesize]
                return render_to_response('smtpmail/sendmailinfo.html',{
                    'mails':groupmails,
                    'page':page,
                    'ps':pagesize,
                    'tolpage':tolpage,
                    'mid':mid
                })
            except Exception,e:
                log.error(e)
            
        return HttpResponse('''{"code":%s,"msg":"%s"}'''%(ecode,einfo))
    return render_to_response('error/404.shtml')
def systemadmin(request):
    '''得到发送邮件列表'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')

    page=int(request.GET.get('page',1))
    pagesize = int(request.GET.get('ps',10))
    is_con = int(request.GET.get('is_con',0))

    username = request.GET.get('username','')
    email = request.GET.get('email','')
    groupid = int(request.GET.get('groupid',0))
    
    where = ''
    if username:
        where += """ and `emailname` like '%%%%%s%%%%' """%username
    
    if email:
        where += """ and `emailadd` like '%%%%%s%%%%' """%email
    
    if groupid:
        where += ''' and `group`=%s'''%groupid
    
    limit = '%s,%s'%((page-1)*pagesize,pagesize)

    cursor=connection.cursor()
    sql = """select `group` from `crm_smtpsendermaillist` where `is_removed`=0 group by `group` order by `group`"""
    cursor.execute(sql)
    group = cursor.fetchall()

    sql = """select * from `crm_smtpsendermaillist` where `is_removed`=0 %s order by `id` desc limit %s"""%(where,limit)
    sql1 = """select count(*) as num from `crm_smtpsendermaillist` where  `id` in(select id from `crm_smtpsendermaillist` where `is_removed`=0 %s) """%where
    cursor.execute(sql)
    mails = cursor.fetchall()
    cursor.execute(sql1)
    tol = cursor.fetchall()
    cursor.close();
    if len(tol)>0:
        tolpage = int(int(tol[0][0])/pagesize)
        if int(tol[0][0])%pagesize !=0:
            tolpage = tolpage+1
    else:
        tolpage = 1
    #mails = smtpsendermaillist.objects.order_by('id')
    #mails = smtpsendermaillist.objects.filter(is_removed=0)
    #paginator=Paginator(mails,10)
    #try:
        #mails = paginator.page(page)
    #except:
        #return HttpResponseRedirect('/glist',{'level':request.session['level']})

    return render_to_response('smtpmail/systemadminlist.html',{
        'tolpage':tolpage,
        'total':tol[0][0],
        'page':page,
        'ps':pagesize,
        'is_con':is_con,
        'mails':mails,
        'email':email,
        'group':group,
        'username':username,
        'ttt':''
    })

def delsysemail(request):
    '''删除发送邮件列表'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    
    if request.is_ajax():
        mid = int(request.GET.get('mid',0))
        if not mid:
            return HttpResponse('''{"code":0,"msg":"Please try again after to refresh the page"}''')
        
        ecode = 0
        einfo = 'fail'
        try:
            try:
                upmaillist = smtpsendermaillist.objects.get(pk=mid)
                upmaillist.is_removed = 1
                upmaillist.save()
            except:
                smtpsendermaillist.objects.get(pk=mid).delete()
            
            ecode = 1
            einfo = 'Successful operation'
        except Exception,e:
            log.error(e)
        return HttpResponse('''{"code":"%s","msg":"%s"}'''%(ecode,einfo))
    
    return render_to_response('error/404.shtml')

def addsysemail(request):
    '''添加新邮件列表'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')

    cursor=connection.cursor()
    sql = """select `group` from `crm_smtpsendermaillist` where `is_removed`=0 group by `group` order by `group`"""
    cursor.execute(sql)
    groups = cursor.fetchall()

    mid = int(request.GET.get('mid',0))
    mails = ['']
    if mid:
        mails = smtpsendermaillist.objects.order_by('id')
        mails = smtpsendermaillist.objects.filter(pk=mid)
    

    return render_to_response('smtpmail/addsysemail.html',{'maillist':mails[0],'groups':groups})

def watch_from_email_details(request):
    '''添加新邮件列表'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')

    groupid = int(request.GET.get('group',0))

    page=int(request.GET.get('page',1))
    pagesize = int(request.GET.get('ps',10))

    if not groupid:
        return HttpResponse('''{"code":0,"msg":"Please try again after to refresh the page"}''')
    
    ecode = 0
    einfo = 'fail'
    maillist = ''
    tolpage = 1
    groupmails = ''
    tol = ''
    try:
        groupmails = smtpsendermaillist.objects.filter(group=groupid,is_removed=0,status=1)
        paginator=Paginator(groupmails,pagesize)
        tolpage = len(range(paginator.num_pages+1)[1:])
        groupmails = groupmails[(page-1)*pagesize:(page)*pagesize]
        tol = smtpsendermaillist.objects.filter(group=groupid).count()
            
    except Exception,e:
        log.error(e)
    return render_to_response('smtpmail/watch_groupmails.html',{
        'mails':groupmails,
        'page':page,
        'pagesize':pagesize,
        'groupid':groupid,
        'tolpage':tolpage,
        'total':tol
        })

def savesysemail(request):
    '''保存新邮件列表'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    if request.is_ajax():
        name = request.POST.get('name','')
        email = request.POST.get('email','')
        pwd = request.POST.get('pwd','')
        smtp = request.POST.get('smtp','')
        status = request.POST.get('status','')
        group = request.POST.get('group',1)
        mid = request.POST.get('id','')
        daylimit = int(request.POST.get('daylimit',100))

        ecode = 0
        einfo = 'Fail,Please try again!'
        try:
            if mid:
                sales2=smtpsendermaillist.objects.filter(Q(emailadd=email),Q(is_removed=0),~Q(pk=mid))
                if sales2:
                    einfo='The email have existed'
                    return HttpResponse('''{"code":"%s","msg":"%s"}'''%(ecode,einfo))
                upmaillist = smtpsendermaillist.objects.get(pk=mid)
                upmaillist.emailname = name
                upmaillist.emailadd = email
                upmaillist.emailpwd = pwd
                upmaillist.smtp_server = smtp
                upmaillist.status = status
                upmaillist.group = group
                upmaillist.daylimit = daylimit
                upmaillist.save()
            else:
                sales2=smtpsendermaillist.objects.filter(emailadd=email,is_removed=0)
                if sales2:
                    einfo='The email have existed'
                    return HttpResponse('''{"code":"%s","msg":"%s"}'''%(ecode,einfo))
                sales=smtpsendermaillist(
                    emailname=name,
                    emailadd=email,
                    emailpwd=pwd,
                    group=group,
                    daylimit=daylimit,
                    senddate='1970-01-01',
                    smtp_server = smtp
                )
                sales.save()
            ecode = 1
            einfo = 'suc'
        except Exception,e:
            log.error(e)
        return HttpResponse('''{"code":"%s","msg":"%s"}'''%(ecode,einfo))

    return render_to_response('error/404.shtml')
    
def uploadfile(request):
    '''上传CSV邮件列表'''
    if not check.checklogin(request):
        return HttpResponseRedirect('/')
    
    if request.method == 'GET':
        return render_to_response('error/404.shtml')
    else:
        file_obj = request.FILES.get('csvfile', None)
        this_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        opt = 0
        einfo = 'File not null!'
        if file_obj:
            import csv
            import StringIO
            buf = StringIO.StringIO(file_obj.read())
            try:
                group = smtpsendmaligroup(
                    group_name=file_obj,
                    add_time = this_time,
                    add_user = request.session['name']
                )
                group.save()
                group = smtpsendmaligroup.objects.get(add_time=this_time)
                groupid = group.id
                del(group)

                reader = csv.reader(buf)
                for row in reader:
                    if len(row)!=5:
                        log.error('%s: File Error!'%file_obj)
                        einfo = 'File Error!'
                        break
                    if row[0]=='' or row[0]=='邮件地址' or row[0]=='email':
                        continue;

                    sendmail = smtpsendmalilist(
                        mail_sendmail=row[0],
                        user_name = row[3],
                        send_state = 2,
                        mailgroup_id = groupid,
                        comefrom = row[1],
                        comefromcode=row[2]
                    )
                    sendmail.save()
                    opt = 1
            except Exception,e:
                log.error(e)
                einfo = e
        
        if opt==1:
            return HttpResponse("""
                <script type="text/javascript" src="/static/js/jquery-1.4.2.min.js"></script>
                <script type="text/javascript" src="/static/js/artDialog/jquery.artDialog.js?skin=default"></script>
                <script type="text/javascript" src="/static/js/artDialog/plugins/iframeTools.js"></script>
                <script>
                    var p=art.dialog.top;
                    p.$('#gmid').val('%s');
                    p.$('#sendto').val('CSV file:%s');
                    p.$('.optinfo').html('Option Successful!')
                    p.$("input[name='uploadfile']").val('Upload')
                    p.$("input[name='uploadfile']").attr('disabled',false)
                    setTimeout(function(){p.$('.optinfo').empty()},10000)
                </script>
                """%(groupid,file_obj))

        else:
            return HttpResponse("""
                <script type="text/javascript" src="/static/js/jquery-1.4.2.min.js"></script>
                <script type="text/javascript" src="/static/js/artDialog/jquery.artDialog.js?skin=default"></script>
                <script type="text/javascript" src="/static/js/artDialog/plugins/iframeTools.js"></script>
                <script>
                    var p=art.dialog.top;
                    p.$('.optinfo').empty()
                    p.$("input[name='uploadfile']").val('Upload')
                    p.$("input[name='uploadfile']").attr('disabled',false)
                    alert("%s!")
                </script>
            """%einfo.replace('"','\''))